package com.rr.learningdemo.exception;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuangcanrun
 * @Date 2021/05/28/15:33
 * @description
 **/

public class Solution {

    Map<Integer, String> map = new HashMap<>();

    @Test
    public void test(){
        //0100
        //1110
        //0010
        int[] a = {0, 7, 9, 6, 2};
        System.out.println(totalHammingDistance(a));
    }

    private int totalHammingDistance(int[] nums) {
        if (nums == null || nums.length == 1) {
            return 0;
        }
        int length = nums.length;
        int result = 0;
        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j++) {
                int count = 0;
                int num1 = nums[i];
                int num2 = nums[j];
                if (num1 == num2) {
                    continue;
                }
                String str1 = map.containsKey(num1) ? map.get(num1) : getBinaryStr(num1);
                String str2 = map.containsKey(num2) ? map.get(num2) : getBinaryStr(num2);
                int str1Len = str1.length();
                int str2Len = str2.length();
                int minLen = Math.min(str1Len, str2Len);
                for (int z = 0; z < minLen; z++) {
                    if (str1.charAt(z) != str2.charAt(z)) {
                        count++;
                    }
                }
                if (str1Len > str2Len) {
                    for (int z = str2Len; z < str1Len; z++) {
                        if (str1.charAt(z)=='1') {
                            count++;
                        }
                    }
                } else if (str1Len < str2Len) {
                    for (int z = str1Len; z < str2Len; z++) {
                        if (str2.charAt(z)=='1') {
                            count++;
                        }
                    }
                }
                System.out.println(num1 + "," + num2 + "," + count);
                result += count;
            }
        }
        return result;
    }


    private String getBinaryStr(int num) {
        int realNum = num;
        StringBuilder binary = new StringBuilder(num % 2 == 1 ? "1" : "0");
        while (num > 0) {
            num >>= 1;
            binary.append(num % 2 == 1 ? "1" : "0");
        }
        String str = binary.toString();
        map.put(realNum, str);
        return str;
    }
}
